#! /usr/local/bin/python
"""reading and exporting VAT files from ArcGIS rasters"""

import os # needed for VATreader function

def VAT_reader(currVATdict_in,read_filename, writeDBF=1, DBF_format="csv", return_table=0, default_output_path=""):
    # read_filename is either the pathname to the raster directory or the full name to the VAT.ADF table within it
    # writeDBF flag controls whether or not to write the VAT contents out to a permanent file
    # DBF_format sets filetype for converted VAT, either ascii CSV, tab TXT, or binary DBF
    # return_table flag controls whether a global dictionary of VALUE, COUNT pairs is modified
    # This dictionary is named "currVATdict" and must exist before function is called whether or not it's used
    # Default output path is the same as the location of the VAT.ADF table unless altered when function is called
    # VAT_reader returns 0 if it fails, or 1 if it succeeds
    # import problems 7-31-07
    ##global currVATdict_in,header_string
    global header_string
    #DBF header variables
    first4bytes='\x03k\x07\x1b'
    next24bytes='a\x00\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00W\x00\x00'
    next32bytes='VALUE\x00\x00\x00\x00\x00\x00N\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    last32bytes='COUNT\x00\x00\x00\x00\x00\x00N\x00\x00\x00\x00\t\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    terminating='\r'
    header_string=first4bytes+"wxyz"+next24bytes+next32bytes+last32bytes+terminating
    
    # first check filename for vat.adf type
    if read_filename[-7:].lower() != "vat.adf":
        # assume only raster pathname was passed in, and add "/vat.adf" to it
        # more complex filename and type checking could be done here
        read_filename = read_filename + "/vat.adf"
    # next test for existence of VAT file
    if not os.path.exists(read_filename):
        print "***WARNING**** "+read_filename+" does not exist, aborting VAT_reader now!!!"
        return 0
    # then test for VAT file size
    readnum = long(os.path.getsize(read_filename))
    if readnum <= 0:
        print "***WARNING**** "+read_filename+" is empty, aborting VAT_reader now!!!"
        return 0
    vat_file = open(read_filename,"rb")
    vat_rows = readnum/8 # value for number of rows in VAT
    stuff = vat_file.read()
    vat_file.close() # done with reading it into memory
    if len(stuff) != readnum:
        print "***WARNING**** "+str(len(stuff))+" != "+str(readnum)+" aborting VAT_reader now!!!"
        return 0
    
    if return_table != 0:
        currVATdict_in = {} # clear out any old values in currVATdict
    if writeDBF==1:
        space10 = "          "
        DBF_format=DBF_format.lower()
        if DBF_format != "txt" and DBF_format != "dbf" and DBF_format != "csv":
            print "***WARNING**** "+DBF_format+" is not a valid format (csv, txt, or dbf). Aborting VAT_reader now!!!"
            return 0
        # open output file
        if default_output_path == "":
            default_output_path = read_filename[:-7]+"/VAT2DBF."+DBF_format
        dbf_file = open(default_output_path,"wb")
        if DBF_format == "csv":
            write_item = "VALUE,COUNT\n" # CSV comma separated value file type
        elif DBF_format == "dbf":
            largest= int(vat_rows / (256**3))
            next_largest=int((vat_rows-largest*(256**3)) / 256**2)
            next_smallest=int((vat_rows-largest*(256**3)-next_largest*(256**2)) / 256)
            smallest=int(vat_rows % 256)
            #print largest
            #print next_largest
            #print next_smallest
            #print smallest
            size_string=chr(smallest)+chr(next_smallest)+chr(next_largest)+chr(largest)
            write_item=header_string[:4]+size_string+header_string[8:]
            # DBF file format from www.cs.cornell.edu/Courses/cs212/2001fa/Project/Part1/dbf.htm"
        elif DDB_format == "txt":
            write_item = "VALUE\tCOUNT\n" # TAB delimited file type extension TXT
        else:
            return 0 # should ever get to this line
        dbf_file.write(write_item)
        
    # everything appears to be OK and ready for function to run    
            
    for rows in range(vat_rows):
        i = rows*8
        a = ord(stuff[i+0:i+1])*256+ord(stuff[i+1:i+2])
        b = ord(stuff[i+2:i+3])*256+ord(stuff[i+3:i+4])
        value = a*65536+b
        x = ord(stuff[i+4:i+5])*256+ord(stuff[i+5:i+6])
        y = ord(stuff[i+6:i+7])*256+ord(stuff[i+7:i+8])
        count = x*65536+y
        if return_table !=0:
            currVATdict_in[value]=count
        if writeDBF==1:
            if DBF_format == "csv":
                write_item = str(value)+","+str(count)+"\n" # CSV file type extension
            elif DBF_format == "dbf":
                write_item = space10[:-len(str(value))]+str(value)+space10[1:-len(str(count))]+str(count) # 10 col value, 9 col count in DBF files
            elif DDB_format == "txt":
                write_item = str(value)+"\t"+str(count)+"\n" # TAB delimited file type
            else:
                return 0 # should ever get to this line
            dbf_file.write(write_item)
        #print "for record # "+str(rows+1)+" ",
        #print "VALUE = "+str(value)+" ",
        #print "COUNT = "+str(count)    
    if writeDBF==1:
        dbf_file.close()
    return 1,currVATdict_in
    # this marks the end of the VAT_reader function()

if __name__ == "__main__":
    pass

    
    
